package edu.cmu.cs.webapp.ioms.actions.order;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.models.OrderStatus;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.views.InventoryView;
import edu.cmu.cs.webapp.ioms.views.OrdersListView;

/**
 * 
 * @author Christian
 * 
 */
public class UpdateOrderStatusViewAction implements IViewActionDelegate {
	private PurchaseOrder model;
	private OrdersListView _view;

	@Override
	public void init(IViewPart view) {
		this._view = (OrdersListView) view;

	}

	@Override
	public void run(IAction action) {
		if (model != null) {
			if (!model.getStatus().equals(OrderStatus.PENDING)) {
				return;
			}

			if (MessageDialog.openConfirm(this._view.getViewSite().getShell(),
					"Accept Confirmation",
					"Are you sure you want to accept this order?")) {
				
				this.model.accept();

				// refresh GUI
				this._view.refreshOrdersView();
				InventoryView iv = InventoryView.getInventoryView(this._view
						.getViewSite());
				if (iv != null) {
					iv.refreshInventoryView();
				}

			}

		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof PurchaseOrder) {
				this.model = (PurchaseOrder) obj;
			}
		}

	}

}
